const state = {
  // 每个商品的信息对象，都包含如下 6 个属性：
  // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
  cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
}
const mutations = {
  //添加商品信息
  addTheGoods(state, pyload) {
    //查询商品是否存在
    const even = state.cart.find(goods =>
      goods.goods_id === pyload.goods_id
    )
    if (even) {
      //存在 数量加一
      even.goods_count++
    } else {
      //不存在则添加
      state.cart.push(pyload)
    }
    this.commit('cart/addCartStorage')
  },
  //将购物车数量持久化本地
  addCartStorage() {
    uni.setStorageSync('cart', JSON.stringify(state.cart))
  },
  //更改商品选中状态
  setGoodsState(state, pyload) {
    const result = state.cart.find(goods => goods.goods_id === pyload.goods_id)
    if (result) {
      result.goods_state = !pyload.goods_state
    }
    this.commit('cart/addCartStorage')
  },
  //更改商品数量
  setGoodsCount(state, {
    goods,
    count
  }) {
    const result = state.cart.find(item => item.goods_id === goods.goods_id)
    if (result) {
      result.goods_count = count
    }
    this.commit('cart/addCartStorage')
  },
  //删除商品信息
  removeGoodsInfo(state, pyload) {
    state.cart = state.cart.filter(item => item.goods_id !== pyload.goods_id)
    this.commit('cart/addCartStorage')
  },
  //全选按钮
  setBeSelectedAll(state, pyload) {
    state.cart.forEach(item => item.goods_state = pyload)
    this.commit('cart/addCartStorage')
  }
}

const getters = {
  //商品总数量
  total(state) {
    // let num = 0
    // state.cart.forEach(item => num += item.goods_count)
    const resutl = state.cart.reduce((count, item) => count += item.goods_count, 0)
    return resutl
  },
  // 商品被选中数量
  selGoodsCount(state) {
    //被选中商品
    const resutl = state.cart.filter(item => item.goods_state)
    return resutl.reduce((count, item) => count += item.goods_count, 0)
  },
  //结算总金额
  goodsTotalAmount() {
    //被选中商品
    const resutl = state.cart.filter(item => item.goods_state)
    return resutl.reduce((count, item) => count += item.goods_count * item.goods_price, 0).toFixed(2)
  }
}

const actions = {}

export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}
